package org.ranshiyan.utils;

import com.google.gson.Gson;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

@Component
@Scope(value= BeanDefinition.SCOPE_SINGLETON)
public class CreditBeanFactory implements ApplicationContextAware {

    @Autowired
    private static ApplicationContext applicationContext;


    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        CreditBeanFactory.applicationContext = applicationContext;
    }

    public static ApplicationContext getApplicationContext() {
        return applicationContext;
    }

/*    public static <T> T getBean(String name) {
        Object bean = applicationContext.getBean(name);
        Gson gson = new Gson();
        gson.fromJson(name.toString(),name);
        return applicationContext.getBean(name);
    }*/

    public static <T> T getBean(String name/*, Class<?> requiredType*/)
            throws BeansException {
        Class type = BeanType.getType(name);
        return (T) applicationContext.getBean(name, type);
    }
}
